/*
 * Singularity Engine
 * Copyright (C) 2010 Vyacheslav Vorobyov, All rights reserved.
 * See LICENSE for full license information.
 */
package org.singularity.io.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.annotation.PostConstruct;

import org.singularity.io.CloseablePipe;

/**
 * @author vjache
 *
 */
@SuppressWarnings("unchecked")
public class PipeLine<T, T1> extends TPipe<T, T1> {
	
	private class TerminalPipe implements CloseablePipe
	{
		@Override
		public void close() throws IOException 
		{getNext().close();}
		@Override
		public void flush() throws IOException 
		{getNext().flush();}
		@Override
		public void push(Object aItem) throws IOException 
		{getNext().push((T1) aItem);}
	}

	private List<TPipe> _pipes;
	private TPipe _head;

	/**
	 * 
	 */
	public PipeLine() {}

	/**
	 * @param aNext
	 */
	public PipeLine(CloseablePipe<T1> aNext, List<TPipe> aPipes) {
		super(aNext);
		setPipes(aPipes);
	}
	
	@PostConstruct
	public void init()
	{
		if(getPipes().size()==0)
			return;
		
		final Iterator<TPipe> pit = getPipes().iterator();
			
		TPipe prev = _head = pit.next();
		while(pit.hasNext())
		{
			final TPipe curr = pit.next();
			prev.setNext(curr);
			prev = curr;
		}
		prev.setNext(new TerminalPipe());
	}

	public void setPipes(List<TPipe> aPipes) 
	{_pipes = aPipes;}
	protected final List<TPipe> getPipes()
	{return _pipes;}

	@Override
	public void push(T aItem) throws IOException 
	{_head.push(aItem);}
	@Override
	public void flush() throws IOException 
	{_head.flush();}
	@Override
	public void close() throws IOException 
	{_head.close();}
}
